//
//  LYDSegmentView.m
//  ZeegingLottery
//
//  Created by 李曌 on 2018/10/18.
//  Copyright © 2018 蒂埃里. All rights reserved.
//

#import "LYDSegmentView.h"

typedef void(^LYDIndexBlock)(NSUInteger ,UIButton *);
int const LYDSegmentHeight = 36;//可根据项目需求设置高度

@interface LYDSegmentView ()

@property (nonatomic, strong, readwrite) NSMutableArray *buttons;
@property (nonatomic, strong, readwrite) UIScrollView *contentView;
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, assign) int segmentHeight;
@property (nonatomic, readwrite) NSUInteger index;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) UIView *separateLine;
@property (nonatomic, strong) UIButton *selectedButton; /**< 当前被选中的按钮*/
@property (nonatomic, strong) UIView *indicateView;     /**< 下滑杠*/
@property (nonatomic, assign) CGFloat indicateHeight;   /**< 下滑杠高度*/
@property (nonatomic, assign, readwrite) NSTimeInterval duration;  /**< 滑动时间*/
@property (nonatomic, assign, readwrite) CGFloat buttonSpace;      /**< 按钮title到边的间距*/
@property (nonatomic, assign) CGFloat minItemSpace;     /**< 最小Item之间的间距*/
@property (nonatomic, assign) CGSize size;
@property (nonatomic, strong) UIFont *font;
@property (nonatomic, copy) LYDIndexBlock indexBlock;



@end

@implementation LYDSegmentView

+ (instancetype)segmentViewWithFrame:(CGRect)frame titles:(NSArray<NSString *> *)titles
{
    return [[self alloc] initWithFrame:frame titles:titles];
}

- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray<NSString *> *)titles
{
    self = [super initWithFrame:frame];
    if (!titles.count || !self) {
        return nil;
    }
    
    _titles = titles;
    _size = frame.size;
    [self segmentSetting];
    [self segmentContentSetting];
    
    return self;
}

- (void)segmentSetting
{
    self.backgroundColor = [UIColor colorWithWhite:1. alpha:0.5];
    _buttons = [NSMutableArray array];
    _segmentHeight = LYDSegmentHeight;
    _minItemSpace = 40.;
    _segmentTintColor = [UIColor blackColor];
    _segmentNormalColor = mainTextColor;
    _font = kFONT_SIZE(16);
    _buttonSpace = [self calculateSpace];
    _indicateHeight = 2.0;
    _duration = 0.3;
    _scrollEnabled = YES;
    _showSeparateLine = NO;
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, _size.width, _segmentHeight);
    
}

- (CGFloat)calculateSpace {
    CGFloat space = 0;
    CGFloat totalWidth = 0;
    
    for (NSString *title in _titles) {
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName : _font}];
        totalWidth += titleSize.width;
    }
    
    space = (_size.width - totalWidth) / _titles.count / 2;
    if (space > _minItemSpace / 2) {
        return space;
    } else {
        return _minItemSpace / 2;
    }
}

- (void)segmentContentSetting
{
    _contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _size.width, _segmentHeight)];
    _contentView.backgroundColor = [UIColor clearColor];
    _contentView.showsHorizontalScrollIndicator = NO;
    _contentView.showsVerticalScrollIndicator = NO;
    _contentView.scrollEnabled = _scrollEnabled;
    
    //下滑杠
    _indicateView = [[UIView alloc] initWithFrame:CGRectZero];
    _indicateView.backgroundColor = _segmentTintColor;
    
    
    CGFloat btnW = _size.width/_titles.count;
    for (int i = 0; i < _titles.count; i++) {
        NSString *title = _titles[i];
        //按钮文字宽度
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: _font}];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(btnW*i, 0,btnW, _segmentHeight);
        [button setTag:i];
        [button.titleLabel setFont:_font];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:_segmentNormalColor forState:UIControlStateNormal];
        [button setTitleColor:_segmentTintColor forState:UIControlStateSelected];
        [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
        [_contentView addSubview:button];
        [_buttons addObject:button];
        
        if (i == 0) {
            button.selected = YES;
            _selectedButton = button;
            
            CGFloat indicateView_x = CGRectGetMaxX(button.frame)/4;
            
            // 添加下滑杠
            _indicateView.size = CGSizeMake(titleSize.width - titleSize.width/3, _indicateHeight);
            _indicateView.layer.cornerRadius = 1.0;
            _indicateView.layer.masksToBounds = YES;
            [_indicateView setCenterX_:indicateView_x*2];
            [_indicateView setY_:_segmentHeight - _indicateHeight];
            [_contentView addSubview:_indicateView];
        }
        
        //导航滚动范围
        self.contentView.contentSize = CGSizeMake(btnW*i, _segmentHeight);
    }
    
    
    [self addSubview:_contentView];
}



#pragma maek - btnClick

- (void)didClickButton:(UIButton *)sender
{
    NSLog(@"%@",sender.titleLabel.text);
    
    if (sender != _selectedButton) {
        sender.selected = YES;
        _selectedButton.selected = NO;
        _selectedButton = sender;
        
        
        [self scrollIndicateView];
//        [self scrollSegementView];
    }
    //点击回调
    if (_indexBlock) {
        _indexBlock(_selectedButton.tag,sender);
    }
    
}

/**
 根据选中的按钮滑动指示杆
 */
- (void)scrollIndicateView
{
//    NSUInteger index = self.index;
    CGSize titleSize = [_selectedButton.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: _font}];
    
    [UIView animateWithDuration:_duration animations:^{
        
//        CGFloat MaxX = CGRectGetMaxX(_selectedButton.frame);
//        CGFloat minX = CGRectGetMinX(_selectedButton.frame);
//        CGFloat x = (MaxX+minX)/2;
        CGFloat x = CGRectGetMidX(_selectedButton.frame);
        CGFloat y = CGRectGetMinY(_indicateView.frame);
        [_indicateView setCenterX_:x];
        [_indicateView setY_:y];
        _indicateView.size = CGSizeMake(titleSize.width - titleSize.width/3, _indicateHeight);
        NSLog(@"x--%f,w--%f",x,(titleSize.width - titleSize.width/3));
        
    } completion:nil];
    
}

/**
 根据选中调整segementView的offset
 */
- (void)scrollSegementView {
    
    CGFloat selectedWidth = _selectedButton.frame.size.width;
    CGFloat offsetX = (_size.width - selectedWidth) / 2;
    
    if (_selectedButton.frame.origin.x <= _size.width / 2) {
        [_contentView setContentOffset:CGPointMake(0, 0) animated:YES];
    } else if (CGRectGetMaxX(_selectedButton.frame) >= (_contentView.contentSize.width - _size.width / 2)) {
        [_contentView setContentOffset:CGPointMake(_contentView.contentSize.width - _size.width, 0) animated:YES];
    } else {
        [_contentView setContentOffset:CGPointMake(CGRectGetMinX(_selectedButton.frame) - offsetX, 0) animated:YES];
    }
}


/// offset
- (void)adjustOffsetXToFixIndicatePosition:(CGFloat)offsetX
{
    
}

- (void)setSelectedAtIndex:(NSUInteger)index
{
    for (UIView *view in _contentView.subviews) {
        if ([view isKindOfClass:[UIButton class]] && view.tag == index) {
            UIButton *button = (UIButton *)view;
            [self didClickButton:button];
            break;
        }
    }
    
}

- (void)selectedAtIndex:(void (^)(NSUInteger, UIButton *))indexBlock {
    if (indexBlock) {
        _indexBlock = indexBlock;
    }
}

- (NSUInteger)index {
    return _selectedButton.tag;
}

#pragma mark - set

- (void)setSeparateColor:(UIColor *)separateColor {
    _separateColor = separateColor;
    
    self.separateLine.backgroundColor = separateColor;
}

- (void)setSegmentTintColor:(UIColor *)segmentTintColor {
    _segmentTintColor = segmentTintColor;
    _indicateView.backgroundColor = segmentTintColor;
    for (UIView *view in _contentView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            [button setTitleColor:segmentTintColor
                         forState:UIControlStateSelected];
        }
    }
}

- (void)setSegmentNormalColor:(UIColor *)segmentNormalColor {
    _segmentNormalColor = segmentNormalColor;
    for (UIView *view in _contentView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            [button setTitleColor:segmentNormalColor
                         forState:UIControlStateNormal];
        }
    }
}

- (void)setScrollEnabled:(BOOL)scrollEnabled {
    _scrollEnabled = scrollEnabled;
    
    _contentView.scrollEnabled = scrollEnabled;
}

- (void)setShowSeparateLine:(BOOL)showSeparateLine {
    _showSeparateLine = showSeparateLine;
    
    _separateLine.hidden = !showSeparateLine;
}

#pragma mark - get

- (int)segmentHeight {
    return _segmentHeight;
}

@end
